import md5 from 'js-md5'

const host='http://pear.apixn.com';
const appid=1;
const appkey='rvhcK4ATMdMvm796GeQTmr8dKzU0NOltpHP72prR48M3aBycGIh9VZ2WexnIH3c5BFgOnpKBktaZiPU8rKQsfh2c3m0Tty9KEob3s8tJjDaAlMOD7iMkej2kHm6JDZCt';

var api={
	getConfig:function(params){
		return params;
	},
	webUrl:function(url){
		url = encodeURIComponent(url);
		console.log(url);
		uni.navigateTo({
			url:'/pages/common/webview?url='+url
		});
	},
	login:function(user){
		uni.setStorageSync('user',user);
		return user;
	},
	getuser:function(){
		var user = uni.getStorageSync('user');
		if(user){
			return user;
		}else{
			return false;
		}
	},
	setuser:function(key,val){
		var user = uni.getStorageSync('user');
		user[key] = val;
		uni.setStorageSync('user',user);
		return user;
	},
	islogin:function(){
		if(this.getuser()){
			uni.switchTab({
			    url: '/pages/my/my'
			});
		}
	},
	logout:function(){
		uni.removeStorageSync('user');
		return false;
	},
	request:function(options){
		var dataObj = {};
		options.method = options.method || 'GET';
		options.formdata = options.formdata || {};
		options.content_type = options.content_type || 'application/x-www-form-urlencoded';
		if(options.method=='GET'){
			var sign = this.sign(options.method,options.url,options.formdata);
		}else{
			var sign = this.sign(options.method,options.url);
			dataObj = options.formdata;
		}
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			var user = uni.getStorageSync('user');
			if(user){
				var token = '.'+user.api_token;
			}else{
				var token = '';
			}
			return uni.request({
				url: sign['url'], 
				data: dataObj,
				method: options.method,
				header: {
				   'Authorization': sign['sign']+token,
				   'content-type': options.content_type,
				},
				success: (res) => {
					uni.hideLoading();
		            if (res.data.code == 0) {
						uni.showToast({
							title: '获取数据失败:' + res.data.msg,
							duration: 1000,
							icon: "none"
						});
						return;
					}else if(res.data.code == 623){
						this.logout();
						uni.showToast({
							title: res.data.msg,
							duration: 1000,
							icon: "none"
						});
						return;
					}else if(res.data.code == 624){
						console.log(res.msg);
						//this.login(res.data);
						//this.request(options)
						return;
					}
					//console.log(res.data)
					resolve(res.data);
				},
				fail: (err) => {
					uni.hideLoading();
					//console.log(err);
					reject(err);
				},
				complete:() => {
					uni.hideLoading();
					//console.log('请求完成');
				}
			});
		});
	},
	upload:function(options){
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '上传中',
				mask: true
			});
			var sign = this.sign('POST',options.url);
			var dataObj = options.formdata;
			var user = uni.getStorageSync('user');
			if(user){
				var token = '.'+user.api_token;
			}else{
				var token = '';
			}
			uni.uploadFile({
				url: sign['url'], 
				filePath: options.file,
				name: options.name,
				formData: dataObj,
				header: {
				   'Authorization': sign['sign']+token,
				   'content-type':'multipart/form-data'
				},
				success: (res) => {
					uni.hideLoading();
					resolve(res.data);
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err);
				},
				complete:() => {
					uni.hideLoading();
				}
			});
		});
	},
	sign:function(method,url,params={}){
		var arr = [];
		arr['t'] = new Date().getTime();
		arr['appkey'] = this.getConfig(appkey);
		arr['nonce'] = this.randomStr(16);
		arr['appid'] = this.getConfig(appid);
		if(method=='GET'){
			for(var index in params){
				arr[index]=params[index];
			}
		}
		var arr_px=[];
		for (var index in arr) {
			arr_px.push(index+'='+arr[index]);
		}
		arr_px.sort();
		arr_px = arr_px.join('&');
		var sign = md5(arr_px);
		arr['sign'] = md5(sign+arr['nonce']);
		var urlArr = [];
		for (var index in arr) {
			if(index=='appkey' || index=='sign'){
			}else{
				urlArr.push(index+'='+arr[index]);
			}
		}
		var res = [];
		res['sign']=arr['sign'];
		res['url']=this.getConfig(host)+url+'?'+urlArr.join('&');
		return res;
	},
	randomStr:(len)=>{
		len = len || 32;
		var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		var maxLen = $chars.length;
		var str = '';
		for (var i = 0; i < len; i++) {
			str += $chars.charAt(Math.floor(Math.random() * maxLen));
		}
		return str;
	}
}
export default api;
